import React, { Component } from 'react'
import store from '../../../redux'
import Api from '../../../config/api'
import axios from 'axios'
import Com from '../../../common/common'

import Table from 'antd/lib/table'
import Button from 'antd/lib/button'
import Navbar from '../../../Component/navbar'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import Input from 'antd/lib/input'
import Select from 'antd/lib/select'
import DatePicker from 'antd/lib/date-picker'
import Form from 'antd/lib/form'
import message from 'antd/lib/message'
import Popconfirm from 'antd/lib/popconfirm'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;

let oper = null;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
            startMonent: null,
            endMoment: null,
        }
    }
    componentDidMount() {
        this.search();
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            phone: this.phoneInput.input.value,
            companyName: this.comInput.input.value,
            name: this.userInput.input.value,
            status: this.stateInput.rcSelect.state.value[0],
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    render() {
        return (
            <Navbar ref={(item) => { oper = item }} className="account-operbar">
                <Form layout="inline">
                    <FormItem label="手机号"><Input style={{ width: '150px' }} ref={(input) => { this.phoneInput = input }} /></FormItem>
                    <FormItem label="公司名"><Input style={{ width: '150px' }} ref={(input) => { this.comInput = input }} /></FormItem>
                    <FormItem label="客户名"><Input style={{ width: '150px' }} ref={(input) => { this.userInput = input }} /></FormItem>
                    <FormItem label="状态">
                        <Select ref={(input) => { this.stateInput = input }} defaultValue=''>
                            <Option value=''>全部</Option>
                            <Option value={1}>审核中</Option>
                            <Option value={2}>已开户</Option>
                            <Option value={3}>已驳回</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                </Form>
            </Navbar>
        )
    }
}

const ValidateOperbar = Form.create()(OperBar);

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1,
            showReModal: false,
            nowRow: ''
        }
    }
    componentDidMount() {
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextprops) {
        this.setState({
            tableData: nextprops.tableData,
            dataNum: nextprops.dataNum,
            currntPage: nextprops.currentPage,
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    open(data) {
        axios.post(Api['openAccount'] + `?id=${data.id}`).then((res) => {
            if (res) {
                this.props.search();
                message.success('操作成功')
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    reject(data) {
        this.setState({
            showReModal: true,
            nowRow: data
        })
    }
    handleReSure() {
        this.props.form.validateFields(['remark'], (err, values) => {
            if (!err) {
                let data = JSON.parse(JSON.stringify(values))
                axios.post(Api['registerReject'] + `?id=${this.state.nowRow.id}&remark=${data.remark}`).then((res) => {
                    if (res) {
                        this.props.search();
                        this.props.form.resetFields();
                        message.success('操作成功');
                        this.setState({
                            showReModal: false
                        })
                    }
                }).catch((error) => {
                    console.log(error)
                })
            }
        });
    }
    handleReCancel() {
        this.setState({
            showReModal: false
        })
    }
    render() {
        const columns = [
            { title: '手机号码', dataIndex: 'phone', key: '1', width: 150 },
            { title: '公司名称', dataIndex: 'companyName', key: '2', width: 220 },
            { title: '客户姓名', dataIndex: 'name', key: '3', width: 200 },
            {
                title: '状态', key: '4', width: 150, render(record) {
                    return <span style={{ color: record.status === 1 ? '#0000ff' : record.status === 2 ? 'green' : 'red' }}>{record.status === 1 ? '审核中' : record.status === 2 ? '已开户' : '已驳回'}</span>
                }
            },
            {
                title: '驳回原因', key: '5', width: 400, render: (record) => {
                    return (
                        <Popconfirm overlayClassName='no-cancel-pop' placement="top" title={record.remark}>
                            <a>{record.remarkAbb}</a>
                        </Popconfirm>
                    )
                }
            },
            { title: '申请时间', dataIndex: 'createTime', key: '6', width: 200 },
            {
                title: '操作',
                key: '7',
                fixed: 'right',
                width: 300,
                render: (record) => {
                    return record.status === 1 ?
                        (<div>
                            <a onClick={this.open.bind(this, record)}>一键开户</a>
                            <a style={{ marginLeft: '10px' }} onClick={this.reject.bind(this, record)}>驳回申请</a>
                        </div>) : null
                }
            }
        ];
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 18 },
            },
        };
        return (
            <div className="account-table" style={{ marginTop: '10px' }}>
                <Table title={(data) => { return '客户注册列表' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1650, y: this.state.tableHeight }}></Table>
                <Modal visible={this.state.showReModal} onCancel={this.handleReCancel.bind(this)} title="驳回" footer={[
                    <Button key="sure" type="primary" onClick={this.handleReSure.bind(this)}>确定</Button>,
                    <Button key="cancel" type="danger" onClick={this.handleReCancel.bind(this)}>取消</Button>
                ]} >
                    <Form>
                        <FormItem label="驳回原因" {...formItemLayout}>
                            {getFieldDecorator('remark', { validateTrigger: 'onBlur', rules: [{ required: true, message: '必填' }, { max: 200, message: '200字以内' }] })(<TextArea rows={3} style={{ width: 300 }} />)}
                        </FormItem>
                    </Form>
                </Modal>
            </div >
        )
    }
}

const ValidateTable = Form.create()(Table1);

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            totalNum: 0,
            tableData: [],
            searchParams: {},
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            loading: true,
            currentPage: 1,
        }
    }
    setParams(obj) {
        let data = JSON.parse(JSON.stringify(obj));
        this.setState({
            searchParams: data,
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['getRegisterUserList'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach(item => {
                    item.key = item.id;
                    if (item.remark) {
                        item.remarkAbb = Com.abbrData(item.remark, 20);
                    }
                })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    render() {
        return (
            <div>
                <ValidateOperbar search={this.setParams.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <ValidateTable
                        search={this.search.bind(this)}
                        tableData={this.state.tableData}
                        dataNum={this.state.totalNum}
                        currentPage={this.state.currentPage}
                        changePageSize={this.changePageSize.bind(this)}
                        changePage={this.changePage.bind(this)}
                    />
                </Spin>
            </div>
        )
    }
}

export default Box